package com.appunity.sdk.sqlite;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.appunity.sdk.sqlite.SQLiteAssetHelper.SQLiteAssetException;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * **************************************************************************
 * <pre>
 * Copied from Github:
 * https://github.com/jgilfelt/android-sqlite-asset-helper.git
 * 
 *  {@link SQLiteAssetHelper}
 *  @author ZhangZhenli
 * </pre>
 * ***************************************************************************
 *
 */
class Utils {

    private static final String TAG = "Utils";
    private static final boolean DEBUG = true;

    public static List<String> splitSqlScript(String script, char delim) {
        List<String> statements = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        boolean inLiteral = false;
        char[] content = script.toCharArray();
        for (int i = 0; i < script.length(); i++) {
            if (content[i] == '"') {
                inLiteral = !inLiteral;
            }
            if (content[i] == delim && !inLiteral) {
                if (sb.length() > 0) {
                    statements.add(sb.toString().trim());
                    sb = new StringBuilder();
                }
            } else {
                sb.append(content[i]);
            }
        }
        if (sb.length() > 0) {
            statements.add(sb.toString().trim());
        }
        return statements;
    }

    public static void writeExtractedFileToDisk(InputStream in, OutputStream outs) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            outs.write(buffer, 0, length);
        }
        outs.flush();
        outs.close();
        in.close();
    }

    public static ZipInputStream getFileFromZip(InputStream zipFileStream) throws IOException {
        ZipInputStream zis = new ZipInputStream(zipFileStream);
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            Log.w(TAG, "extracting file: '" + ze.getName() + "'...");
            return zis;
        }
        return null;
    }

    public static String convertStreamToString(InputStream is) {
        return new Scanner(is).useDelimiter("\\A").next();
    }

    static List<String> preExeSQL(String sql) {
        List<String> sqlList = new LinkedList<String>();
        String[] temp = sql.split(";");
        String t = null;
        for (int i = 0; i < temp.length; i++) {
            if (t == null) {
                t = temp[i];
            } else {
                t = t + ";" + temp[i];
            }
            System.out.println(t);
            if (t.matches("[\\s\\S]*[\\W]+BEGIN[\\W]+[\\s\\S]*")) {
                if (t.matches("[\\s\\S]*[\\W]+END[\\W]*[\\s\\S]*")) {
                    sqlList.add(t.trim());
                    t = null;
                }
            } else {
                sqlList.add(t.trim());
                t = null;
            }
        }
        return sqlList;
    }

    static void exeSQL(String sql, SQLiteDatabase db) {
        if (sql != null) {
            // 处理SQL语句
            List<String> sqlList = splitSqlScript(sql, ';');
            //
            try {
                for (String cmd : sqlList) {
                    Log.d(TAG, "cmd=" + cmd);
                    if (cmd.trim().length() > 0) {
                        try {
                            db.execSQL(cmd);
                        } catch (SQLException e) {
                            SQLiteAssetHelper.SQLiteAssetException se = new SQLiteAssetHelper.SQLiteAssetException(
                                    "The execution SQL statement error at: " + cmd);
                            throw se;
                        }
                    }
                }
            } catch (SQLiteAssetHelper.SQLiteAssetException e) {
                e.printStackTrace();
                throw e;
            } finally {
                if (db != null) {
                    db.close();
                }
            }
        }
    }

}
